package com.gateway.video.rtsp.server.transport.rtcp.bootstrap;

import com.gateway.video.rtsp.server.config.VideoServerConfig;
import com.gateway.video.rtsp.server.transport.rtp.handler.RtpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.net.URI;

@Slf4j
@RequiredArgsConstructor
public class RtcpServerBootstrap extends Bootstrap implements InitializingBean {
    private final EventLoopGroup group;

    @Autowired
    private VideoServerConfig videoServerConfig;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        group(group);

        option(ChannelOption.SO_BROADCAST, true);
        channel(NioDatagramChannel.class);
        handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            protected void initChannel(NioDatagramChannel ch) throws Exception {
                ch.config().setAutoRead(false);
                ch.pipeline().addLast(applicationContext.getBeanProvider(RtpServerHandler.class).getObject());
            }
        });

        var bind = URI.create(videoServerConfig.getRtcp().getBind());
        bind(bind.getHost(), bind.getPort()).addListener(future -> {
            if (future.isSuccess()) {
                if (log.isInfoEnabled()) {
                    log.info("gateway video rdp has bind address, {}", bind);
                }
            }
        });
    }
}
